'use strict';

const Service = require('egg').Service;

class LoadingService extends Service {
  async index(query) {
    query = query || {};
    const params = {};
    const sort = query.sortOrder ? query.sortOrder.toUpperCase() : 'DESC';
    const Op = this.app.Sequelize.Op;

    params.order = [[ 'id', sort ]];
    params.raw = true;
    params.offset = query.offset ? parseInt(query.offset) : 0;
    params.limit = query.limit ? parseInt(query.limit) : 999;
    params.sortOrder = query.sortOrder || 'desc';
    params.where = {};

    delete query.offset;
    delete query.limit;
    delete query.sortOrder;
    delete query.page;

    for (const key in query) {
      params.where[key] = {
        [Op.like]: `%${query[key]}%`,
      };
    }

    params.include = [{
      model: this.ctx.model.Wms.Basic.Store,
      as: 'store',
      attributes: [[ 'title', 'storeName' ]],
    }, {
      model: this.ctx.model.Wms.Basic.Corp,
      as: 'corp',
      attributes: [[ 'title', 'corpName' ]],
    }];

    try {
      return await this.ctx.model.Wms.Business.Loading.findAndCountAll(params);
    } catch (e) {
      return e.message;
    }
  }

  async new(data) {
    const { ctx } = this;
    // 校验data是否有必需字段
    const params = {
      carno: data.carno || '无',
      checkno: data.checkno || '无',
      WareHouseBillCode: data.WareHouseBillCode || '无',
      loadType: data.loadType,
      loadTime: data.loadTime,
      store_id: Number(data.store_id) || 0,
      corp_id: Number(data.corp_id) || 0,
      owner: data.owner,
      description: data.description,
      status: data.status === '1' ? 1 : 0,
    };

    try {
      const result = await ctx.model.Wms.Business.Loading.create(params);
      return result;
    } catch (e) {
      return e.message;
    }
  }

  async edit(id, data) {
    const { ctx } = this;
    const field = {};
    for (const key in data) {
      if (data[key]) {
        field[key] = data[key];
      }
    }

    try {
      const result = await ctx.model.Wms.Business.Loading.update(field, { where: { id } });
      return result;
    } catch (e) {
      return e.message;
    }
  }

  async show(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wms.Business.Loading.findOne({ where: { id }, raw: true });
      return result;
    } catch (e) {
      return e.message;
    }

  }

  async destroy(id) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Wms.Business.Loading.destroy({ where: { id } });
      return result;
    } catch (e) {
      return e.message;
    }
  }
}

module.exports = LoadingService;
